package com.haoshuang.zhouzhoubang.ui.page.settled.pay

import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import com.alipay.sdk.app.PayTask
import com.haoshuang.zhouzhoubang.config.Config
import com.haoshuang.zhouzhoubang.databinding.ActivityAnnualFeePayBinding
import com.haoshuang.zhouzhoubang.model.event.WechatPaySuccessEvent
import com.haoshuang.zhouzhoubang.ui.page.settled.pay.success.AnnualFeePaySuccessActivity
import com.haoshuang.zhouzhoubang.utils.PayResult
import com.haoshuang.zhouzhoubang.utils.PaymentUtil
import com.haoshuang.zhouzhoubang.utils.PreferenceUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.mufeng.libs.base.BaseVMActivity
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.ktx.getString
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.click
import com.mufeng.libs.utils.view.clickWithTrigger
import com.tencent.mm.opensdk.openapi.WXAPIFactory


/**
 *  年费缴纳页面
 */
class AnnualFeePayActivity : BaseVMActivity<AnnualFeePayViewModel, ActivityAnnualFeePayBinding>() {

    companion object {
        fun launch(context: Context) {
            context.startPage<AnnualFeePayActivity>()
        }
    }

    // 合作年数
    private var year = 0

    // 缴费金额
    private var money = ""

    // 支付方式 1微信2支付宝
    private var payment = 0

    override fun initIntent() {
        year = intent.getIntExtra("year", 0)
        money = intent.getString("fee")
    }

    override fun initView(savedInstanceState: Bundle?) {

        binding.titleBar.title = "门店年费"
        binding.titleBar.leftImageView().click { finish() }

        binding.apply {
            tvPayMoney.text = "$money"
            tvTime.text = "${year}年"
            tvMoney.text = "￥$money"

            llWechat.clickWithTrigger {
                if (payment == 1) return@clickWithTrigger
                payment = 1
                ivWechatPay.isSelected = true
                ivAliPay.isSelected = false
            }

            llAliPay.clickWithTrigger {
                if (payment == 2) return@clickWithTrigger
                payment = 2
                ivWechatPay.isSelected = false
                ivAliPay.isSelected = true
            }

            tvPay.clickWithTrigger {
                if (payment == 0) {
                    toast("请选择支付方式")
                    return@clickWithTrigger
                }
//                money = "0.01"
                if (payment == 1) {
                    //   toast("微信支付")
                    vm.getWechatPayParams(
                        "order_amount" to money,
                        "pay_type" to "1"
                    )
                } else {
                    // toast("支付宝支付")
                    vm.getAliPayParams(
                        "order_amount" to money,
                        "pay_type" to "2"
                    )
                }

            }


        }

    }

    override fun initData() {

    }

    override fun startObserve() {
        vm.getAliPayParamsData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                payAlipay(it?.body!!)
            }
        }
        vm.getWechatPayParamsData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                val api = WXAPIFactory.createWXAPI(mActivity, Config.WX_ID, false)
                PreferenceUtils.putString("Wxpay","10")
                PaymentUtil.payWxPayment(api,it)
            }
        }

        LiveEventBus.get(WechatPaySuccessEvent::class.java).observe(this) {
            // 微信支付成功
            startPage<AnnualFeePaySuccessActivity>()
        }
    }

        private val SDK_PAY_FLAG = 1
        private fun payAlipay(orderNo: String) {
            val payRunnable = Runnable {
                val alipay = PayTask(mActivity)
                val result = alipay.payV2(orderNo, true)
                val msg = Message()
                msg.what = SDK_PAY_FLAG
                msg.obj = result
                mHandler.sendMessage(msg)
            }
            // 必须异步调用
            val payThread = Thread(payRunnable)
            payThread.start()
        }

        @SuppressLint("HandlerLeak")
        var mHandler: Handler = object : Handler() {
            override fun handleMessage(msg: Message) {
                when (msg.what) {
                    SDK_PAY_FLAG -> {
                        val payResult = PayResult(msg.obj as Map<String?, String?>)


                        val resultInfo = payResult.result
                        val resultStatus = payResult.resultStatus

                        if (TextUtils.equals(resultStatus, "9000")) {
                            toast("支付成功")
                            startPage<AnnualFeePaySuccessActivity>()
                            finish()
                        } else {
                            toast("支付失败")
                        }
                    }

                    else -> {}
                }
            }
        }

    }